package cc.opcol.iot.server.repo;

import cc.opcol.iot.server.domain.IEntity;
import cc.opcol.iot.server.util.OpcolUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
public class BaseMongoRepository {
    static Logger logger= LoggerFactory.getLogger(BaseMongoRepository.class);
    @Autowired
    MongoTemplate mongoTemplate;

    public <T> List<T> queryAllByIdDesc(Class<T> t,String nameSpace) {
        List<T> list=new ArrayList<>();
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC,"_id"));
        List<Map> dataMap= mongoTemplate.find(query,Map.class,nameSpace);
        for(Map map:dataMap){
            try {
                list.add((T) OpcolUtil.mapToObject(map,t));
            }catch (Exception e){
                logger.error("",e);
            }
        }
        return list;
    }

    public <T> T getOne(Class<T> t ,Long id,String nameSpace) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Map map=mongoTemplate.findOne(query,Map.class,nameSpace);
        if(map!=null){
            return (T) OpcolUtil.mapToObject(map,t);
        }
        return null;
    }

    public <T> T getOne(Class<T> t,String key,String value,String nameSpace){
        Query query = new Query();
        query.addCriteria(Criteria.where(key).is(value));
        Map map=mongoTemplate.findOne(query,Map.class,nameSpace);
        if(map!=null){
            return (T) OpcolUtil.mapToObject(map,t);
        }
        return null;
    }

    public void save(IEntity object, String nameSpace) {
        if(object.getId()==null || object.getId().longValue()==0){
            object.setId(System.currentTimeMillis());
        }
        Map map=OpcolUtil.objectToMap(object);
        map.put("_id",object.getId());
        mongoTemplate.save(map,nameSpace);
    }

    public void delete(Long id,String nameSpace) {
        Query query=new Query(Criteria.where("_id").is(id.longValue()));
        long count = mongoTemplate.remove(query,Map.class,nameSpace).getDeletedCount();
    }
}
